package org.kimoji.comment.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.kimoji.comment.dao.CommentDAO;
import org.kimoji.common.MultiData;
import org.kimoji.entity.Comment;
import org.kimoji.entity.User;
import org.kimoji.personal.dao.PersonalDAO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class CommentService {

	@Autowired
	private CommentDAO commentDAO;
	@Autowired
	private PersonalDAO personalDAO;
	
	public List<Comment> getCommentsByItemId(String itemId,int page){
		int start = (page-1)*10;
		int end = start+9;
		//查詢對應主題的評論
		List<Comment> comments = commentDAO.getCommentsByItemId(itemId, start, end);
		if(null != comments && comments.size()>0){
			//取出評論中的用戶id
			Set<String> ids = new HashSet<String>();
			for(Comment comment : comments){
				ids.add(String.valueOf(comment.getUser().getId()));
			}
			//根據用戶id查詢用戶的信息
			Map<Integer,User> users = personalDAO.getUsersByUserIds(ids);
			//將用戶信息插入對應評論中
			for(Comment comment : comments){
				int id = comment.getUser().getId();
				User user = users.get(id);
				comment.setUser(user);
			}
		}
		
		return comments;
	}
	
	public boolean saveComment(Comment comment){
		comment.setCreateTime(new Date());
		return commentDAO.saveComment(comment);
	}
	
}
